from concurrent.futures.thread import ThreadPoolExecutor

from flask import Flask, Blueprint
import logging
import logging.handlers
import os
import sys
import signal

pro_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(pro_path)
sys.path.append('..')

from blueprint import register

app = Flask(__name__)
app.secret_key = "djskla"
app.config['JSON_AS_ASCII'] = False


def init_logs():
    root_logger = logging.getLogger()
    for h in root_logger.handlers:
        root_logger.removeHandler(h)

    FORMAT = r'[%(asctime)s][%(levelname)s] %(message)s'
    logging.basicConfig(format=FORMAT, level=logging.DEBUG)
    kDirLog = "logs"
    rotatingFile = logging.handlers.TimedRotatingFileHandler(os.path.join(kDirLog, 'oa.logs'), when='midnight')
    rotatingFile.setFormatter(logging.Formatter(FORMAT))
    logging.getLogger('').addHandler(rotatingFile)
    errorRotatingFile = logging.handlers.TimedRotatingFileHandler(os.path.join(kDirLog, 'oa_err.logs'), when='midnight')
    errorRotatingFile.setFormatter(logging.Formatter(FORMAT))
    errorRotatingFile.setLevel(logging.ERROR)
    logging.getLogger('').addHandler(errorRotatingFile)


def terminat_handler(signalnum, frame):
    logging.debug("server has received:%d signal" % signalnum)
    # db.db_close()


def os_signal_reg():
    logging.debug("regist os signal SIGINT:%d SIGHUP:%d SIGTERM:%d" % (signal.SIGINT, signal.SIGHUP, signal.SIGTERM))
    for sig in [signal.SIGINT, signal.SIGHUP, signal.SIGTERM]:
        signal.signal(sig, terminat_handler)


init_logs()
# os_signal_reg()
register.register_blueprint(app)

if __name__ == "__main__":
    print(app.url_map)
    logging.debug(app.url_map)
    app.run(debug=True, host='192.168.49.128', port='4700')
